<?php


namespace Biz\model\advertisement;

class MHhzDepartmentAdType extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'hhz_department_ad_type';

    const IS_DELETED_YES = 1;
    const IS_DELETED_NO = 0;

    public static function updateDepartmentAdType($departmentId, $adTypes)
    {
        if (!$departmentId) {
            return;
        }

        $existedAdTypes = self::getValidAdTypesByDepartmentId($departmentId);

        $needToDelete = array_diff($existedAdTypes, $adTypes);
        if ($needToDelete) {
            $where = [
                'department_id' => $departmentId,
                'ad_type_id' => $needToDelete,
            ];
            self::update(['is_deleted' => self::IS_DELETED_YES, 'deleted_at' => date('Y-m-d H:i:s')], $where);
        }

        $needToInsert = array_diff($adTypes, $existedAdTypes);
        if ($needToInsert) {
            $insertData = [];

            foreach ($needToInsert as $d) {
                $insertData[] = [
                    'department_id' => $departmentId,
                    'ad_type_id' => $d,
                ];
            }

            self::insert($insertData);
        }

    }

    /**
     * @param $departmentId
     * @return array|bool
     */
    public static function getValidAdTypesByDepartmentId($departmentId)
    {
        return self::select("ad_type_id", [
            'department_id' => $departmentId,
            'is_deleted' => self::IS_DELETED_NO,
        ]);
    }
}
